<?php
class DocumentIndexpController   extends Zone_Action{
	public function Fields($default=NULL){
		$data = array(
			type 	=> array(
				type 		=> 'INT',

				form_label	=> 'Loại tài liệu',
			),
			title 	=> array(
				type 		=> 'INT',
				no_empty 	=>true,
				form_label	=> 'Tiêu đề',
			),
			content	=>array(
				type			=>'HTML',
				form_label		=>'Mô tả tài liệu',
				default_value=>Null
			),
			pub =>array(
				type			=>'INT',
				form_label 		=>'Public',
				default_value	=>0

			),
			date_updated =>array(
				type			=>'DATETIME',
				form_label 		=>'Ngày giờ chỉnh sửa',
				default_value	=>date("Y-m-d H:i:s")
			),
			updated_by_id =>array(
				type			=>'INT',
				form_label		=>'Chỉnh sửa',
				default_value	=>get_user_id()
			)
		);
		/* Neu chinh sua thi cac thong so duoc mac dinh trc */
		if( is_array( $default ) ){
			foreach( $data as $k => $config ){
				if( $config['type'] != 'NONE' && isset( $default[$k] ) ){
					$data[$k]['default_value'] = $default[$k];
				}
			}
		}
		return $data;
	}
	public function depAction(){
		$this->removeLayout();
		$dep = $this->getDepartments(0);
		$this->setContent($dep);
	}
	public function forwardAction(){
		$document_id = getInt("ID",0);

		$this->removeLayout();
		$dep.="<form method='post' action='".actionUrl($this)."' onsubmit='return ajax_form(this)' >";
		$dep.= $this->getDepartments(0);
		$dep.="<br/>
		<input type='hidden' value='".$document_id."' name='document_id' />
		<input type='submit' value='Thực hiện' class='x-button x-save' />
		<input type='reset' value='Bỏ chọn' class='x-button x-fresh' />
		</form>";
		$this->setContent($dep);
		if(isPost()){
			$arrToFoward = $_POST['nametoforward'];
			$document_id =$_POST['document_id'];
			for($i=0;$i<count($arrToFoward);$i++){
				$this->Model->delete("documents_users","`document_id`='$document_id' AND `user_id`='$i'");
			}

			$this->insertDocumentUser($document_id, $arrToFoward);
			$crDoc = $this->Model->fetchRow("SELECT * FROM `documents` WHERE `ID`='$document_id'");
			$this->sendMessage(
				$arrToFoward,
				"Bạn vừa nhận được một tài liệu mới",
				$crDoc['title'],
				"<a href=#Document/Indexp/View?ID=$document_id> Xem chi tiết </a>."
			);
			return $this->setJSON(array(
				redirect => "#Document/Indexp/View?ID=".$document_id
			));
		}
	}

	function insertDocumentUser($document_id,$arrToSend,$is_implement=null,$is_guest=null){
		for($i=0;$i<count($arrToSend);$i++){
			$data = array(
				"document_id"	=>$document_id,
				"user_id"		=>$arrToSend[$i],
			);
			$this->Model->insert("documents_users",$data);
		}
	}

	public function FolderFields($default=NULL){
		$data = array(
			title => array(
				type => 'TEXT',
				no_empty => true,
				form_label => 'Tên thư mục',
				min_length	=> 4,
				max_length	=> 30,
			),
			create_by_id => array(
				type 			=> 'NONE',
				default_value	=>	get_user_id()
			),
			desc => array(
				type => 'TEXT',
				form_label => 'Mô tả',
			)
		);
		/* Neu chinh sua thi cac thong so duoc mac dinh trc */
		if( is_array( $default ) ){
			foreach( $data as $k => $config ){
				if( $config['type'] != 'NONE' && isset( $default[$k] ) ){
					$data[$k]['default_value'] = $default[$k];
				}
			}
		}
		return $data;
	}

	public function initAction(){

		$user_id = get_user_id();
		$this->set('users',$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$user_id'"));

		$sqlDocumentType="SELECT * FROM `documents_types`";
		$arDocumentType=$this->Model->fetchAll($sqlDocumentType);
		$this->set('documentType',$arDocumentType);

		$arType = $this->getDocumentType();

		$this->set('documentTypeLayout',$arType);
		$this->view->listDiplomaSide = $this->getMyFolder();
		$this->view->departments = $this->Model->fetchAll("select * FROM `departments`");
	}

	function getMyFolder(){
		$id=get_user_id();
		$sql="select * FROM `documents_folder` WHERE `create_by_id`='$id'";
		$arr = $this->Model->fetchAll($sql);
		return $arr;
	}

	function getDocumentType(){
		$arrType = $this->Model->fetchAll("select * FROM `documents_types` ");
		return $arrType;
	}

	/*Index Action*/
	public function indexAction(){

		$folder_id = getInt("folder_id",0);

		$user_id = get_user_id();
		$vars = array();
		$WHERE = array();
		$order_by = " ORDER BY `a`.`ID` DESC";

		$current_page = max(getInt('p',1),1);
		$range_page = max(getInt('rp',10),10);

		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}

		if( isset($_REQUEST['rp'])){
			$vars['rp'] = $range_page;
		}
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";

		$field_order = array('title','date_created','created_by_id','filename');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;
			}
		}
		$condition="";

		if($folder_id!=0){

			$sqlTotal="SELECT COUNT(*) as `total`
				FROM `documents` as `a`
					LEFT JOIN `documents_folder_rep` as `b` ON `b`.`document_id`=`a`.`ID`
				WHERE `a`.`is_draft`='no'  AND `a`.`pub`='no' AND `b`.`folder_id`='$folder_id'";
			$sql = "
			SELECT `a`.*,`b`.`username`,`c`.`filename`,`c`.`ID` as `file_id`
			FROM `documents` as `a`
				LEFT JOIN  `users` as `b` on `b`.`ID`=`a`.`created_by_id`
				LEFT JOIN `documents_files` as `c` on `c`.`document_id`=`a`.`ID`
				LEFT JOIN `documents_folder_rep` as `d` on `d`.`document_id`=`a`.`ID`
			WHERE `a`.`is_draft`='no' AND `a`.`pub`='no' AND `d`.`folder_id`='$folder_id' $order_by $limit";

			$arrTypeF = $this->Model->fetchRow("SELECT * FROM `documents_folder` WHERE `ID`='$folder_id'");
			$this->set('x_title',$arrTypeF['title']);
		}else{
			$f = $_GET["t"];
			if(strlen($f)==0){
				$f = "md";
			}
			if($f=="md"){

				$this->set('x_title',"Tài liệu cá nhân");
				$sqlTotal="SELECT COUNT(*) as `total`
					FROM `documents` as `a`
					WHERE `a`.`is_draft`='no' AND `a`.`pub`='no' AND `a`.`created_by_id`='$user_id'";

				$sql="
				SELECT `a`.*,`b`.`username`,`c`.`filename`,`c`.`ID` as `file_id`
				FROM `documents` as `a`
					LEFT JOIN  `users` as `b` ON `b`.`ID`=`a`.`created_by_id`
					LEFT JOIN `documents_files` as `c` ON `c`.`document_id`=`a`.`ID`
				WHERE `a`.`is_draft`='no' AND `a`.`pub`='no' AND `a`.`created_by_id`='$user_id'
					 $order_by $limit";

			}
			if($f=="diS"){

				$this->set('x_title',"Tài liệu được chia sẻ");
				$sqlTotal="SELECT COUNT(*) as `total`
					FROM `documents` as `a`
					LEFT JOIN `documents_users` as `b` ON `b`.`document_id`=`a`.`ID`
					WHERE `a`.`is_draft`='no' AND `a`.`pub`='no' AND `b`.`user_id`='$user_id'";
				$sql="
				SELECT `a`.*,`b`.`username`,`c`.`filename`,`c`.`ID` as `file_id`
				FROM `documents` as `a`
					LEFT JOIN  `users` as `b` ON `b`.`ID`=`a`.`created_by_id`
					LEFT JOIN `documents_files` as `c` ON `c`.`document_id`=`a`.`ID`
					LEFT JOIN `documents_users` as `e` ON `e`.`document_id`=`a`.`ID`
				WHERE `a`.`is_draft`='no' AND `a`.`pub`='no' AND `e`.`user_id`='$user_id' GROUP BY `c`.`document_id` $order_by $limit";
			}
		}

		$total = $this->Model->fetchOne($sqlTotal);

		$posts = $this->Model->fetchAll($sql);

		$a = $vars;
		unset($a['p']);

		$page = page_ajax('#Document/Indexp?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);

		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			documents	=> $posts,
			user_id =>get_user_id()
		));

	}

	public function saveAction(){
		$this->removeLayout();
		$user_id = get_user_id();
		$document_id = getInt("ID",0);
		$folder = $this->Model->fetchAll("select * FROM `documents_folder` WHERE `create_by_id` = '$user_id'");
		if(count($folder)==0){
			return $this->setJSON(array(
				alert => error("Bạn phải tạo thư mục để thực hiện lưu tài liệu")
			));
		}
		$strHtml.="
		<div class='x-form-container'>
		<form method='post' onsubmit='return ajax_form(this)' action='".actionUrl($this)."'>
		<input type='hidden' name='document_id' value='".$document_id."'/>
		<table class='x-form' width='100%' cellpadding='4px'>
			<tr>
				<td class='x-form-label' style='text-align:left'>Chọn thư mục để lưu</td>
			</tr>";
		$strHtml.= "
			<tr>
				</td><select name='folder_id' class='x-select' style='width:170px'>";
		foreach ($folder as $k=>$v){
			$strHtml.="<option value=".$v['ID'].">".$v['title']."</option>";
		}
		$strHtml.="</select>
				</td></tr>";

		$strHtml.="<tr><td align='center'><input type='submit' value='Lưu' class='x-button x-save'/></td></tr></table></form></div>";
		$this->setContent($strHtml);
		if(isPost()){
			$folder_id = $_POST['folder_id'];
			$document_id = $_POST['document_id'];
			$arrDocument = array(
				"document_id"=>$document_id,
				"folder_id"=>$folder_id
			);
			$this->Model->delete("documents_folder_rep","`folder_id`='$folder_id' AND `document_id`='$document_id'");
			$this->Model->insert("documents_folder_rep",$arrDocument);
			return $this->setJSON(array(
				alert =>success("Lưu tài liệu thành công.")
				//redirect => "#Document/Indexp/Index?folder_id=$folder_id"
			));
		}
	}
	//upload
	public function uploadAction(){
		$this->removeLayout();
		$document_id = getInt("ID",0);
		$user_id = get_user_id();
		if( isPost()){
			loadClass("ZData");
			$f = new ZData();
			$f->addField(array(
				file => array(
					type 		=> 'FILE',
					path		=> 'files/document/',
					no_empty	=> true
				)
			));

			$data = $f->getData();
			if( is_array( $data ) ){
				$file = $data['file'];
				$this->Model->insert("documents_files",array(
					document_id		=> $document_id,
					name			=> $file[0],
					type			=> $file[1],
					size			=> $file[2],
					filename		=> $file[3]
				));

				$file_id = $this->Model->lastId();
				return $this->setJSON(array(
					content	=> "<div class='x-file-info'><input checked type='checkbox' name='files[]' value='$file_id'/>
								<a href='".ctrUrl($this)."/File?ID=$file_id' target='_blank'>{$file[3]} {$file[2]} KB	</a>
								</div>"
				));
			}else{
				return $this->setJSON(array(
					alert => error($data)
				));
			}
		}
	}

	public function addAction(){

		$user_id = get_user_id();
		$post = $this->Model->fetchRow( "SELECT * FROM `documents` WHERE `created_by_id`='$user_id' AND `is_draft`='yes' LIMIT 1" );
		if($post && $post['pub']=='no'){
			$document_id = $post['ID'];
            $file = $this->Model->fetchAll( "SELECT * FROM `documents_files` where `document_id`='$document_id'" );

		}else{
			$this->Model->insert("documents",array(
				is_draft		=> 'yes',
				pub 			=> 'no',
				created_by_id	=> $user_id,
				date_created 	=> date('Y-m-d H:i:s')
			));
			$document_id = $this->Model->lastId();
            $post=array();
            $file=array();
		}

        $this->set(array(
            post =>$post,
            files =>$file,
            document_id =>$document_id
        ));
        if(isPost()){
			$document_id = getInt('document_id',0);
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->Fields());
			$data = $form->getData();
			if( is_array($data)){
				$data['is_draft']='no';
				$data['pub']='no';
				$check = $this->Model->update("documents",$data,"`ID`='$document_id'");
				//post ben form mang nguoi dung
				$userV = (array)$_POST['usersView'];
				$roles = array();
				$this->Model->delete("documents_users"," `document_id`='$document_id'");
				//insert vao documents_users
				foreach( $userV as $k => $uid ){
					$roles[$uid] = array(
						document_id		=> $document_id,
						user_id			=> $uid,
						is_view			=> 'yes'
					);
				}

				foreach( $roles as $role ){
					$this->Model->insert('documents_users',$role);
				}
               $crDoc = $this->Model->fetchRow("SELECT * FROM `documents` WHERE `ID`='$document_id'");
				$this->sendMessage(
					$userV,
					"Bạn vừa nhận được một tài liệu mới",
					$crDoc["title"],
					"<a href='#Document/Indexp/View?ID=".$document_id."'>Xem chi tiết</a>"
				);
                ////////////////////
				$files_selected = (array)$_POST['files'];
				$files = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`=$document_id");
				foreach( $files as $f ){
					if( !in_array( $f['ID'], $files_selected ) ){
						$this->Model->delete("documents_files","`ID`='{$f['ID']}'");
						@unlink("files/document/{$f['name']}");
					}
				}
				////////////////////
				return $this->setJSON(array(
					redirect	=> "#Document/Indexp/Index"
				));
			}else{
				return $this->setJSON(array(
					message => error($data)
				));
			}
		}
	}
	public function editAction(){
		$document_id = get("ID",0);
		$user_id = get_user_id();

		$sqlDocumentType="select * FROM `documents_types`";
		$arDocumentType=$this->Model->fetchAll($sqlDocumentType);

		$this->set('documentType',$arDocumentType);
		$post = $this->Model->fetchRow("SELECT `a`.* FROM `documents` as `a`
			LEFT JOIN `documents_users` as `b` ON `a`.`ID`=`b`.`document_id`
			WHERE `a`.`ID`='$document_id'");
		if(!$post){
			return $this->setJSON(array(
				message	=> error('Tài liệu không tồn tại hoặc đã bị xóa trước đó.')
			));
		}
		if($post["created_by_id"]!=get_user_id()){
			return $this->setJSON(array(
				alert	=> error('Bạn không có quyền sửa tài liệu này.')
			));
		}
		$files = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`='$document_id'");

		$sqlUserView = "
				SELECT `a`.* FROM `users` as `a`
				LEFT JOIN `documents_users` as `b` on `a`.`ID`=`b`.`user_id`
				WHERE `b`.`document_id`='$document_id' and `b`.`is_view`='yes' group by `a`.`ID`";
		$usersView = $this->Model->fetchAll($sqlUserView);

		$this->set(array(
			post		=> $post,
			files		=> $files,
			usersView 	=> $usersView,
			usersEdit 	=> $usersEdit
		));

		if(isPost()){
			$document_id = $_POST["ID"];
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->Fields($post));
			$data = $form->getData();
			if( is_array($data)){
				$data['is_draft']='no';
				$check = $this->Model->update("documents",$data,"`ID`='$document_id'");
				//post ben form mang nguoi dung
				$userV = (array)$_POST['usersView'];
				//insert vao documents_users

				$this->Model->delete("documents_users"," `document_id`='$document_id'");
   	            $roles = array();
				//insert vao documents_users
				foreach( $userV as $k => $uid ){
					$roles[$uid] = array(
						document_id		=> $document_id,
						user_id			=> $uid,
						is_view			=> 'yes'
					);
				}
				//////////////////////////////////

				foreach( $roles as $role ){
					$this->Model->insert('documents_users',$role);
				}
				$crDoc = $this->Model->fetchRow("SELECT * FROM `documents` WHERE `ID`='$document_id'");
				$this->sendMessage(
					$userV,
					"Bạn vừa nhận được một tài liệu mới",
					$crDoc["title"],
					"<a href='#Document/Indexp/View?ID=".$document_id."'>Xem chi tiết</a>"
				);
                /////////////////
				$files_selected = (array)$_POST['files'];
				$files = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`=$document_id");
				foreach( $files as $f ){
					if( !in_array( $f['ID'], $files_selected ) ){
						$this->Model->delete("documents_files","`ID`='{$f['ID']}'");
						@unlink("files/document/{$f['name']}");
					}
				}
				/////////////////
				return $this->setJSON(array(
					redirect	=> "#Document/Indexp/Index"
				));
			}else{
				return $this->setJSON(array(
					message => error($data)
				));
			}
		}
	}

public function addfolderAction(){
		$this->removeLayout();
		$table.='
		<div class="x-form-container">
		<form action="'.actionUrl($this).'" method="post" onsubmit="return ajax_form(this)">
		<div class="form-message"></div>
		<table  cellpadding="4px" class="x-form">
			<tr>
				<td width="100" class="x-form-label" w>Tên folder :</td>
				<td><input style="width:287px" type="text" name="title" class="x-text" /></td>
			</tr>
			<tr>
				<td width="100" class="x-form-label">Mô tả :</td>
				<td>
					<textarea style="width:290px" class="x-text" name="desc"></textarea>
				</td>
			</tr>
			<tr>
				<td colspan="4" align="center">
					<input type="submit" value="Tạo mới" class="x-button x-save"/>
					<input type="reset" value="Làm mới" class="x-button x-fresh"/>
				</td>
			</tr>
		</table>
		</form>
		</div>
		';
		$this->setContent($table);
		if(isPost()){
			loadClass("ZData");
			$form = new ZData();
			$form->addFields($this->FolderFields());
			$data = $form->getData();
			if( is_array($data)){
				$check = $this->Model->insert("documents_folder",$data);
				$folder_id = $this->Model->lastId();

				if(!$check){
					return $this->setJSON(array(
						message	=> error('Không thêm được thư mục')
					));
				}
				return $this->setJSON(array(
					redirect	=> "#Document/Indexp/Index?folder_id=$folder_id"
				));
			}else{
				return $this->setJSON(array(
					message	=> error($data)
				));
			}
		}
	}
	public function editfolderAction(){
		$this->removeLayout();
		$id = $_GET['ID'];
		$crFolder = $this->Model->fetchRow("SELECT * FROM `documents_folder` WHERE ID='$id'");
		$table.='
		<div class="x-form-container">
		<form action="'.actionUrl($this).'" method="post" onsubmit="return ajax_form(this)">
		<input type="hidden" value="'.$id.'" name="folder_id" />
		<div class="form-message"></div>
		<table width="365px" cellpadding="4px" class="x-form">
			<tr>
				<td><b>Tên folder</b></td>
			</tr>
			<tr>
				<td><input style="width:320px;" value="'.$crFolder['title'].'" type="text" name="title" class="x-text" /></td>
			</tr>
			<tr>
				<td><b>Mô tả</b></td>
			</tr>
			<tr>
				<td>
					<textarea style="width:320px;"  class="x-text" name="desc">'.$crFolder['desc'].'</textarea>
				</td>
			</tr>
			<tr>
				<td colspan="2" align="right">
					<input type="submit" value="Sửa" class="x-button x-save"/>

				</td>
			</tr>
		</table>
		</form>
		</div>
		';
		$this->setContent($table);
		if(isPost()){
			$folder_id = $_POST['folder_id'];
			loadClass("ZData");
			$form = new ZData();
			$form->addFields($this->FolderFields($crFolder));
			$data = $form->getData();
			if( is_array($data)){
				$check = $this->Model->update("documents_folder",$data," `ID`='$folder_id' ");
				if(!$check){
					return $this->setJSON(array(
						message	=> error('Không sửa được thư mục')
					));
				}
				return $this->setJSON(array(
					redirect	=> "#Document/Indexp/Index?folder_id=$folder_id"
				));
			}else{
				return $this->setJSON(array(
					message	=> error($data)
				));
			}
		}
	}

	public function viewAction(){
		$document_id=getInt('ID',0);
		$chk = $this->Model->fetchRow("SELECT * FROM `documents` WHERE `ID`='$document_id'");
		if($chk['title']==""){
			return $this->setJSON(array(
				alert	=> error("Tài liệu không tồn tại hoặc đã bị xóa trươc đó")
			));
		}
		$arCrDoc  = $this->Model->fetchRow("
		SELECT `a`.*,`b`.`title` as `document_type`,`c`.`username`,c.`username` as `updated_by_name`
		FROM `documents` as `a`
			LEFT JOIN `documents_types` as `b` ON `b`.`ID`=`a`.`type`
			LEFT JOIN `users` as `c` ON `c`.`ID`=`a`.`created_by_id`
		WHERE `a`.`ID`='$document_id'");

		$file = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`='$document_id'");
		$topRight = $this->Model->fetchRow("
			SELECT `a`.`updated_by_id`,`a`.`date_updated`,`b`.`username` as `updated_by_name`
			FROM `documents` as `a`
			LEFT JOIN `users` as `b` ON `a`.`updated_by_id`=`b`.`ID`
			WHERE `a`.`ID`='$document_id'
		");

		$listToSend = $this->Model->fetchAll("
		SELECT `a`.*,`b`.*,`b`.`ID` as `user_id` FROM `documents_users` as `a`
		LEFT JOIN `users` as `b` on `b`.`ID`=`a`.`user_id`
		WHERE `a`.`document_id`='$document_id' AND `a`.`is_view`='yes' GROUP BY `b`.`ID`");

		$listToEdit = $this->Model->fetchAll("
		SELECT `a`.*,`b`.*,`b`.`ID` as `user_id` FROM `documents_users` as `a`
		LEFT JOIN `users` as `b` on `b`.`ID`=`a`.`user_id`
		WHERE `a`.`document_id`='$document_id' AND `a`.`is_process`='yes' GROUP BY `b`.`ID`");

		$this->set(array(
            listToSend 		=>	$listToSend,
			listToEdit 		=> 	$listToEdit,
            crDocument      =>	$arCrDoc,
			files 			=>	$file,
			cr_update       =>	$topRight
        ));
	}


	public function deleteAction(){
		$id=getInt("ID",0);
		$chk = $this->Model->fetchRow("SELECT * FROM `documents` WHERE `ID`='$id'");


    		if($chk['created_by_id']!=get_user_id()){
    			return $this->setJSON(array(
    				alert =>error('Bạn không có quyền xóa tài liệu này')
    			));
    		}else{
				$files = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`='$id'");
				foreach( $files as $f ){
						$this->Model->delete("documents_files","`ID`='{$f['ID']}'");
						@unlink("files/document/{$f['name']}");
				}
				$this->Model->delete("documents"," `ID`='$id' ");
    		}


		if(is_array($_POST['checkbox_diploma'])){
			$id = $_POST["checkbox_diploma"];
			if(empty($id)===true){
				return $this->setJSON(array(
					alert =>error('Chưa có tài liệu nào được chọn.')
				));
			}
			for($i=0;$i<count($id);$i++){
				$k = $id[$i];
				$files = $this->Model->fetchAll("SELECT * FROM `documents_files` WHERE `document_id`='$k'");
				foreach( $files as $f ){
						@unlink("files/document/{$f['name']}");
				}
			}
			$strID = "(".join(",",$id).")";
			$this->Model->delete("documents","`ID` in $strID AND `created_by_id`='$user_id'");
		}

		return $this->setJSON(array(
			redirect	=> "#Document/Indexp"
		));
	}
	public function deletefolderAction(){
		$folder_id = getInt("ID",0);
		$check = $this->Model->delete("documents_folder","`ID`='$folder_id'");
		if($check){
			return $this->setJSON(array(
				redirect	=> "#Document/Indexp/Index"
			));
		}
	}
	/*get deparment*/
	protected function getDepartments( $id, $depth = 0, $SELECTed='', $name='users' ){
		//Lay phong ban con
		$sub_departments
			= $this->Model->fetchAll("SELECT `a`.*,IF(`b`.`ID`,`b`.`ID`,0) as `parentID`
				FROM `departments` as `a`
				LEFT JOIN `departments` as `b` ON
				`a`.`parent_id`=`b`.`ID` HAVING `parentID`='$id'");
		$staffs = $this->Model->fetchAll("select *,IF( '$SELECTed' LIKE CONCAT('%,',`ID`,'%') , ' checked', '' ) as
        `checked`  FROM `users` WHERE `department_id`='$id'");

		if(count($staffs) == 0 && count($sub_departments) == 0){
			return '';
		}

		//class
		$class = $depth == 0 ? "tree-list tree-root":"tree-list";

		$list = "<div class='tree-list-outer'>
			<div class=\"$class\">";
		foreach( $sub_departments as $k => $sub ){
			$subs = $this->getDepartments( $sub['ID'], $depth+1, $SELECTed );

			$cl = $subs !="" ? "" : " tree-link-empty";
			$cls = $subs !="" ? "" : " tree-folder-empty";

			//show child in depth
			$has_sub  = $this->Model->fetchOne("select * FROM `departments` WHERE `parent_id`='{$sub['ID']}'");
			$is_close = $has_sub ? "" : " tree-section-close";

			$list .="<div class='tree-folder-outer'>
				<a class='tree-node' onclick='tree_collapse(this)'></a>
				<div class='tree-folder'>
					<a class='tree-title'><input type='checkbox' class='tree-check' onclick='tree_check_all(this)'/>{$sub['title']}</a>
					$subs
				</div></div>";
		}

		foreach( $staffs as $k => $staff ){
			$list .="<a class='tree-item-outer'>
				<span class='tree-item'><span class='tree-item-icon'></span>
				<input type='checkbox' name='nametoforward[]' value='{$staff['ID']}'{$staff['checked']}' class='tree-check'/>".$staff['username']."</span>
				</a>";
		}
		$list .="</div></div>";
		return $list;
	}


 	function sendMessage($user_id, $content,$title,$url){
 		for($i=0;$i<count($user_id);$i++){
			$this->Model->insert("notices",array(
				created_by_id   => get_user_id(),
				user_id			=> $user_id[$i],
				title			=> $title,
				url				=> $url,
				content			=> $content,
				date			=> mysql_date()
			));
 		}
	}

}
?>